package com.shujiaotong.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.R;
import com.shujiaotong.mapper.OrderDetailMapper;
import com.shujiaotong.pojo.*;
import com.shujiaotong.service.IOrderDetailService;
import com.shujiaotong.service.IOrdersService;
import com.shujiaotong.service.IShopService;
import com.shujiaotong.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IShopService shopService;
//    分页
    @GetMapping("page")
    public R page(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) Integer status
    ){
        log.info("当前页:{},页条数:{},类型:{}", page, pageSize, status);
        Page<Orders> ordersPage = ordersService.getOrdersWithDetails(page, pageSize, status);
        return R.success(ordersPage);
    }

//    通过orders表的orderid列，查询orderdetail表的creattime、endtime、description列,
//    并且加在查询出来的order里面，order实体类里面有相应的字段


//    下单
    @PostMapping("/placeOrder")
    public R placeOrder(@RequestBody Orders orders) {
        // 1. 获取前端传来的参数 userId 用户 id shopId 商品 id shopCount 商品数量
        Long userId = orders.getUserId();
        log.info("userId: {}", userId);
        Long shopId = orders.getShopId();
        Integer shopCount = orders.getShopCount();

        // 2. 检查 shopCount 的有效性
        if (shopCount <= 0) {
            return R.error("商品数量必须大于0");
        }

        // 3. 根据用户 id 和商品 id 获得商品和用户信息
        User user = userService.getById(userId);
        Shop shop = shopService.getById(shopId);

        // 4. 判断商品是否在售
        if (shop == null) {
            return R.error("商品不存在");
        }

        if (shop.getStatus() == 1) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCreateTime(LocalDateTime.now());
            // 假设结束时间为创建时间加上一个小时
            orderDetail.setEndTime(LocalDateTime.now().plusHours(1));

            // 设置订单信息
            orders.setUserId(userId);
            orders.setShopId(shopId);
            orders.setShopCount(shopCount);

            // 确保商品价格不为 null
            if (shop.getNewPrice() == null) {
                return R.error("商品价格不存在");
            }

            // 计算账户金额
            BigDecimal account = shop.getNewPrice().multiply(BigDecimal.valueOf(shopCount));
            orders.setAccount(account);
            orders.setStatus(1);
            orders.setShopName(shop.getShopName());
            orders.setPhone(user.getPhone());
            orders.setImage(shop.getImage());
            orders.setPrice(shop.getNewPrice());

            // 保存 OrderDetail
            if (orderDetailService.save(orderDetail)) {
                orders.setOrderId(orderDetail.getId()); // 获取保存后的 ID
                if (ordersService.save(orders)) {
                    return R.success("下单成功");
                } else {
                    return R.error("下单失败，订单未保存，请联系管理员");
                }
            } else {
                return R.error("下单失败，订单明细未保存，请联系管理员");
            }
        } else {
            return R.error("商品已停售");
        }
    }

//    查询已购商品
    @GetMapping
    public R getOrderByUserId(@RequestParam Long userId,
                              @RequestParam(required = false) String shopName){
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId, userId);

        if (!StringUtils.isEmpty(shopName)){
            qw.like(Orders::getShopName, shopName);
        }

        // 查询所有订单
        List<Orders> ordersList = ordersService.list(qw);

        // 通过订单 ID 填充订单详情
        ordersList.forEach(order -> fillOrderDetails(order));

        // 排序
        ordersList.sort(Comparator.comparing(Orders::getCreateTime).reversed());

        return R.success(ordersList);
    }


    /**
     * 通过订单 ID 查询订单详情并填充到 Orders 对象中
     */
    private void fillOrderDetails(Orders order) {
        OrderDetail detail = orderDetailMapper.selectById(order.getOrderId());
        if (detail != null) {
            order.setCreateTime(detail.getCreateTime());
            order.setEndTime(detail.getEndTime());
            order.setDescription(detail.getDescription());
        }
    }


    //    删除订单
    @DeleteMapping
    public R deleteOrder(@RequestParam Long id){
        boolean b = ordersService.removeById(id);
        return b?R.success("删除成功"):R.error("删除失败");
    }


}
